package com.zzzy.framework.common.util;


import com.baomidou.mybatisplus.annotation.TableField;
import com.zzzy.common.vo.SortingField;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Set;

public class SortFieldUtil {

    public static Set<SortingField> getSortingFields(Class<?> clazz, String orderField, String orderRule) {
        if (StringUtils.isBlank(orderField)){
            return Collections.emptySet();
        }
        String tableFieldName = getTableFieldName(clazz, orderField);
        SortingField sortingField = SortingField.builder().field(tableFieldName).order(orderRule).build();
        return Collections.singleton(sortingField);
    }

    /**
     * 通过实体类字段获取对应的表字段名称
     *
     * @param clazz 实体类
     * @param fieldName 字段名称
     * @return 对应的表字段名称
     */
    private static String getTableFieldName(Class<?> clazz, String fieldName) {
        Field field = ReflectionUtils.findField(clazz, fieldName);
        if (field == null) {
            throw new IllegalArgumentException("Field not found: " + fieldName);
        }

        TableField tableField = field.getAnnotation(TableField.class);
        if (tableField != null && StringUtils.isNotBlank(tableField.value())) {
            return tableField.value();
        }

        return fieldName;
    }
}
